package com.webserver.core;

import com.webserver.http.HttpServletRequest;

import java.io.*;
import java.net.Socket;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;

/**
 * 当前线程任务负责与指定的客户端进行交互
 * 1解析请求
 * 2处理请求
 * 3发送响应第四步
 * 当一个客户端连接进入这个线程上就相当与接通一个电话然后进行上面三部操作
 */
public class ClientHandler implements Runnable {
    //定义一个套接字(电话)属性第五步
    private Socket socket;
    //构造方法里面赋值 第六步
    public ClientHandler(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {

        try {
           //解析请求第二十三步
            HttpServletRequest request = new HttpServletRequest(socket);
            String path = request.getUri();
            System.out.println("抽象路径"+path);
            //处理请求



            //发送响应
            //第三十步定位类加载路径
            File root = new File(ClientHandler.class.getClassLoader().getResource(".").toURI());
            //static路径根据类加载路径找到的
            File staticDir = new File(root,"static");
            //根据static找到index (改成根据抽象路径（path）找到地址)
            File file = new File(staticDir,path);
            //将socket转换成字符输入流发送出去第三十一步
            //OutputStream out = socket.getOutputStream();
            //1发送状态行转成数组发送第三十二步
           // String line = "HTTP/1.1 200 OK";
            //第三十六步掉方法传入字符串
                println("HTTP/1.1 200 OK");

            //2发送响应头第三十三步
            //line = "Content-Type: text/html";
            //第三十七步掉方法传入字符串(改造前看注释代码)
            println("Content-Type: text/html");
            println("Content-Length: "+file.length());
            //line ="Content-Length: "+file.length();
            //单独输出空格回车表示响应头部分发送完毕
//            out.write(13);
//            out.write(10);
            println("");
            //3发送响应正文第三十四步
            OutputStream out = socket.getOutputStream();
            FileInputStream fis = new FileInputStream(file);
            byte[] buf =new byte[1024*10];
            int len;
            while ((len=fis.read(buf))!=-1) {
                out.write(buf,0,len);
            }


        } catch (IOException | URISyntaxException e) {
            e.printStackTrace();
        }finally {

            try {
                //交互完毕断开连接
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

    }
    //第三十五步将消息转成数组发送 做成一个方法
        private void println(String line) throws IOException {
            OutputStream out = socket.getOutputStream();
            byte[] data = line.getBytes(StandardCharsets.ISO_8859_1);
            out.write(data);
            out.write(13);
            out.write(10);
        }


}
